package com.design3.graduatethesissys.common.utils;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.design3.graduatethesissys.service.impl.UserServiceImpl;

/** 
* @author 作者 罗穆健: 
* @version 创建时间：2020年1月10日 下午3:10:39 
* 类说明 
*/
@Component
public class ResetPasswordUtils {
	
	@Autowired
	private UserServiceImpl userServiceImpl;
    public static ResetPasswordUtils resetPasswordUtils;
    
    @PostConstruct
    public void init() {
    	resetPasswordUtils = this;
    	resetPasswordUtils.userServiceImpl =this.userServiceImpl;
    }

	/** 前端只用传旧密码和新密码和确认密码
	 * @param oldPassword
	 * @param newPassword
	 * @return 新密码和确认密码不同返回 error01,新密码和旧密码相同返回error02,旧密码和数据库存的密码不同返回error03,修改成功返回success,修改失败返回false
	 */
	public static String resetPassword(String oldPassword,String newPassword,String confirmPassword) {
		PasswordEncoder encoder = new BCryptPasswordEncoder();
		User userInfo = (User) resetPasswordUtils.userServiceImpl.loadUserByUsername(GetUserName.getUserName());
		if (!encoder.matches(oldPassword,userInfo.getPassword())) {
			return "旧密码不正确";
		}else if(oldPassword.equals(newPassword)) {
			return "新密码和旧密码不能相同";
		}else if(!newPassword.equals(confirmPassword)) {
			return "新密码和确认密码不同";
		}
		newPassword = encoder.encode(newPassword);
		return resetPasswordUtils.userServiceImpl.resetPassword(newPassword);
	}
}
 